package com.librelato.persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import com.librelato.negocio.bean.IBeanGenerico;
import com.librelato.persistencia.config.SQLConfiguracao;
import com.librelato.persistencia.interfaces.IDaoGenerico;

public abstract class DaoGenerico<P extends IBeanGenerico> implements
		IDaoGenerico<P> {

	protected Connection conn;
	protected String query;
	protected PreparedStatement ps;
	protected ResultSet rs;
	protected SimpleDateFormat df, df2;

	protected void fecharRecursos(PreparedStatement ps, ResultSet rs)
			throws Exception {

		try {
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

	protected String buscaNomeFornecedor(String codigo, String loja)
			throws Exception {
		String nome = "";
		PreparedStatement ps2;
		ResultSet rs2;	
		String query2;
		try {
			conn = GerenciadorConexao.getConexao();
			query2 = SQLConfiguracao.getInstance().getValor(
					"localiza_nome_fornece");
			ps2 = conn.prepareStatement(query2);
			ps2.setString(1, codigo);
			ps2.setString(2, loja);
			rs2 = ps2.executeQuery();
			if (rs2.next()) {
				nome = rs2.getString("A2_NOME");
			}
		} catch (Exception e) {
			throw e;
		} 
		return nome;
	}

	protected String formatar(String valor, String mascara) {

		String dado = "";
		for (int i = 0; i < valor.length(); i++) {
			char c = valor.charAt(i);
			if (Character.isDigit(c)) {
				dado += c;
			}
		}

		int indMascara = mascara.length();
		int indCampo = dado.length();

		for (; indCampo > 0 && indMascara > 0;) {
			if (mascara.charAt(--indMascara) == '#') {
				indCampo--;
			}
		}

		String saida = "";
		for (; indMascara < mascara.length(); indMascara++) {
			saida += ((mascara.charAt(indMascara) == '#') ? dado
					.charAt(indCampo++) : mascara.charAt(indMascara));
		}
		return saida;
	}
}
